package com.earthea.common.util;

import junit.framework.TestCase;
import lombok.Data;

import java.util.List;
import java.util.Map;

public class JacksonUtilsTest extends TestCase {

    public void testIsJson() {
        String json1 = "{\"key1\":\"value1\",\"key2\":\"value2\"}";
        assertTrue(JacksonUtils.isJsonMap(json1));
        assertFalse(JacksonUtils.isJsonArray(json1));
        String json2 = "[\"key1\",\"value1\",\"key2\",\"value2\"]";
        assertTrue(JacksonUtils.isJsonArray(json2));
        assertFalse(JacksonUtils.isJsonMap(json2));
    }

    public void testToJson() {
        String json1 = "{\"key1\":\"value1\",\"key2\":\"value2\"}";
        String json2 = "[\"key1\",\"value1\",\"key2\",\"value2\"]";

        Map<String, String> map = JacksonUtils.fromJsonMapQuietly(json1, String.class, String.class);
        assertEquals("value1", map.get("key1"));
        assertEquals("value2", map.get("key2"));
        String json11 = JacksonUtils.toJson(map);
        assertEquals(json1, json11);

        List<String> list = JacksonUtils.fromJsonArray(json2, String.class);
        assertEquals("key1", list.get(0));
        assertEquals("value1", list.get(1));
        assertEquals("key2", list.get(2));
        assertEquals("value2", list.get(3));
        String json22 = JacksonUtils.toJson(list);
        assertEquals(json2, json22);

        TestBean testBean = JacksonUtils.fromJson(json1, TestBean.class);
        assertEquals("value1", testBean.getKey1());
        assertEquals("value2", testBean.getKey2());
    }

    @Data
    private static class TestBean {
        private String key1;

        private String key2;
    }
}